<template>
  <view class="coupon-center" :data-theme="themeName">
    <view class="coupon-header flex row-between" @click="show = !show">
      <view class="nr normal">优惠券</view>
      <view>
        <template v-if="selectedCoupons.length > 0">
          <text class="m-r-20 sm primary">-¥{{ totalDiscount }}</text>
        </template>
        <template v-else>
          <text class="muted nr m-r-20" v-if="couponList.usable.length <= 0">暂无可用优惠券</text>
          <text class="mini-tag" v-else>{{ couponList.usable.length }}张可用</text>
        </template>
        <u-icon name="arrow-right" size="22rpx" color="#696969"></u-icon>
      </view>
    </view>

    <u-popup class="popup" v-model="show" mode="bottom" height="1000rpx" :closeable="true" border-radius="20">
      <view class="title normal bold">优惠券</view>
      <u-tabs font-size="28" name="tabsName" inactive-color="#333" :active-color="themeColor" :list="list"
        :is-scroll="false" :current="current" @change="change" :show-bar="false">
      </u-tabs>

      <scroll-view scroll-y="true" class="content bg-body">
        <view v-show="current == 0">
          <template v-if="couponList.usable.length">
            <block v-for="(item, index) in couponList.usable" :key="item.id">
              <view @click="toggleCoupon(index, item)">
                <coupon-card :index="index" :params="item" type="checkbox"
                  :checked="isSelected(item.cl_id)" @check="toggleCoupon(index, $event)"></coupon-card>
              </view>
            </block>
            <view class="confirm-btn">
              <u-button type="primary" shape="circle" @click="confirmSelection" style="background-color: #E26028;">确定</u-button>
            </view>
          </template>
          <u-empty v-else text="暂无优惠券" mode="coupon" margin-top="150"></u-empty>
        </view>

        <view v-show="current == 1">
          <template v-if="couponList.unusable.length">
            <block v-for="(item, index) in couponList.unusable" :key="item.id">
              <coupon-card :params="item" type="" :unusable="true"></coupon-card>
            </block>
          </template>
          <u-empty v-else text="暂无优惠券" mode="coupon" margin-top="150"></u-empty>
        </view>
      </scroll-view>
    </u-popup>
  </view>
</template>

<script>
import { apiOrderBuyCouponList } from '@/api/store.js'
import { formatMoney } from '@/utils/tools';
export default {
  data() {
    return {
      show: false,
      couponList: {
        usable: [],
        unusable: []
      },
      list: [{
        name: '可使用优惠券'
      },
      {
        name: '不可使用优惠券'
      }
      ],
      current: 0,
      selectedCoupons: [], // 存储最终选中的优惠券
      tempSelected: [], // 临时存储选择状态
    }
  },
  computed: {
    totalDiscount() {
      const sum = this.selectedCoupons.reduce((total, coupon) => {
        // 使用可选链操作符和默认值处理可能的null/undefined
        const couponValue = parseFloat(coupon?.money) || 0;
        return total + couponValue;
      }, 0);
      
      // 确保返回格式化的金额字符串
      return sum.toFixed(2);
    }
  },
  created() {
    this.getOrderBuyCoupon()
  },

  methods: {
    change(index) {
      this.current = index
    },

    // 判断是否选中
    isSelected(id) {
      return this.tempSelected.includes(id)
    },

    // 切换优惠券选择状态
    toggleCoupon(index, item) {
      const couponId = item.cl_id || item.id
      if (this.isSelected(couponId)) {
        this.tempSelected = this.tempSelected.filter(id => id !== couponId)
      } else {
        // 检查优惠券是否可叠加
        if (!this.checkCombinable(item)) {
          this.tempSelected = [couponId] // 不可叠加则只保留当前选择的
        } else {
          this.tempSelected.push(couponId)
        }
      }
    },

    checkCombinable(coupon) {
      // 这里根据业务逻辑实现优惠券叠加规则
      // 示例：检查是否有不可叠加的优惠券已被选中
      return true // 默认允许叠加
    },

    // 确认选择
   confirmSelection() {
     this.selectedCoupons = this.tempSelected.map(id => 
       this.couponList.usable.find(c => (c.cl_id || c.id) === id)
     ).filter(Boolean);
     
     this.$emit('change', {
       couponIds: this.tempSelected,
       totalDiscount: this.totalDiscount // 使用计算属性
     });
     this.show = false;
   },

    getOrderBuyCoupon() {
      apiOrderBuyCouponList({
        shop_id: this.shopData.id
      }).then((res) => {
        this.list[0].name = `可使用优惠券(${res.data.usable.length})`
        this.list[1].name = `不可使用优惠券(${res.data.unusable.length})`
        this.couponList = res.data
      })
    }
  }
}
</script>

<style lang="scss" scoped>
	/deep/ .u-btn--primary{
		border-color: #E26028 !important;
		background-color:#E26028 !important;
	}
	/deep/ .u-btn {
	   background-color: #E26028 !important;
	   border-color: #E26028 !important;
	 }
	.confirm-btn {
		padding: 30rpx;
		margin-top: 20rpx;
		
	}

	.coupon-center {
		.primary {
			@include font_color();
		}

		.coupon-header {
			padding: 20rpx;

			&--scroll-view {
				width: 500rpx;
				height: 46rpx;
				white-space: nowrap;
			}
		}

		.popup {
			.title {
				padding: 30rpx 20rpx;
			}

			.content {
				padding: 20rpx;
				box-sizing: border-box;
				height: 80%;
			}

			.confirm-btn {
				padding: 30rpx;
				margin-top: 20rpx;
			}
		}

		// 标签
		.mini-tag {
			color: #ffffff;
			border-radius: 4rpx;
			padding: 4rpx 20rpx;
			margin-right: 16rpx;
			@include background_color();
			font-size: $-font-size-xxs;
		}

		// 镂空
		.plain {
			border-width: 1rpx;
			border-style: solid;
			@include border_color();
			@include font_color();
			background: none !important;
		}
	}
</style>